import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:zhrs/api/api.dart';
import 'package:zhrs/model/user_model.dart';
import 'package:zhrs/utils/http_utils.dart';
import 'package:zhrs/utils/randowcode.dart';
class Login_verificationcode extends StatefulWidget {
  String phonenumber;
  Login_verificationcode(this.phonenumber);
  @override
  State<StatefulWidget> createState()=>_Login_verificationcode();
}
class  _Login_verificationcode extends State<Login_verificationcode>
{
  String  verificationcode="";

  String randomcode= RandomCode().randomcode(6);
  Timer timer;
  Widget changewiget;
  int countnumber=60;
  TextEditingController _textcontroller = new TextEditingController();
  static bool once=true;
  FocusNode _focusNode =new  FocusNode();
  _greykuang greykuang =new  _greykuang();
  _bluekuang bluekuang =new  _bluekuang();
  List<Widget> kuang=[];

  @override
  void initState()  {
    // TODO: implement initState
    super.initState();

    try
    {
      Timer t=Timer.periodic(new Duration( seconds: 1), (val){

        FocusScope.of(context).requestFocus(_focusNode);
        val.cancel();
      });
    }
  catch(e)
    {}
for(int i=0;i<6;i++)
  {
    kuang.add(greykuang);
  }

    _textcontroller.addListener(() {
      if (_textcontroller.text.length < 6) {
        for (int i = 0; i < 6; i++) {
          if (i != _textcontroller.text.length) {
            kuang[i] = greykuang;
          }
          else {
            kuang[_textcontroller.text.length] = bluekuang;
          }
        }
      }

      if (_textcontroller.text.length == 6) {
        if (randomcode == _textcontroller.text) {
          if (widget.phonenumber.endsWith("0") ||
              widget.phonenumber.endsWith("1") ||
              widget.phonenumber.endsWith("2") ||
              widget.phonenumber.endsWith("3"))
            HttpManager.login(
                context, UserModel(loginname: "111111", password: "111111"),
                true);
          if (widget.phonenumber.endsWith("4") ||
              widget.phonenumber.endsWith("5") ||
              widget.phonenumber.endsWith("6") ||
              widget.phonenumber.endsWith("7"))
            HttpManager.login(
                context, UserModel(loginname: "222222", password: "222222"),
                true);
          if (widget.phonenumber.endsWith("8") ||
              widget.phonenumber.endsWith("9"))
            HttpManager.login(
                context, UserModel(loginname: "333333", password: "333333"),
                true);
          alertDialog(this.context, "验证成功").then((va){
          });
        }
        else {
          if(once){
            once=false;
            _textcontroller.text = "";
            print("进去了");
            for (int i = 0; i < 6; i++) {
              if (i == 0) {
                kuang[i] = bluekuang;
              }
              else
                kuang[i] = greykuang;
            }
            FocusScope.of(context).requestFocus(_focusNode);
            alertDialog(context, "验证码错误").then((va){
              once=true;
              _textcontroller.text = "";
            });
            _textcontroller.text = "";
          }
        }
      }
      setState(() {
      });
    });
    httprquest();
    changewiget=changewidges(false);
    timer = new Timer.periodic(new Duration(seconds: 1), (timer){
    print(countnumber);
      countnumber--;
      if(countnumber==0)
        {
          changewiget=  changewidges(true);
          countnumber=60;
          timer.cancel();
        }
      else changewiget=  changewidges(false);
      setState(() {
      });
    });
  }
 Widget  changewidges(bool isfinish){
    if(isfinish)
      {
        return   FlatButton(
            color: Colors.blue,
            onPressed: (){
              randomcode= RandomCode().randomcode(6);
              print("randomcode:"+randomcode);
              try{
                HttpUtils().post("https://www.dzsbk.cn/smartDemo/wdssc-app/sms",data: "{'phoneNumbers':'"+widget.phonenumber+"','code':'"+randomcode+"'}").then((v){
                  v.toString();
                });
              }
              catch(e)
              {
                alertDialog(context,"服务异常").then((val)
                {
                  Navigator.pop( context);
                });
                return;
              }
              timer= new Timer.periodic(new Duration(seconds: 1), (timer){
                print(countnumber);
                countnumber--;
                if(countnumber==0)
                {
                  changewiget=  changewidges(true);
                  countnumber=60;
                  timer.cancel();
                }
                else changewiget=  changewidges(false);
                setState(() {
                });
              });
            },
            child: Text(
              "重新发送",style: TextStyle(color: Colors.white),
            ),
          );
      }
    else{
      return Text("重新发送"+countnumber.toString()+"s");
    }
   }
  String secretnumber()
  {
  return  widget.phonenumber.replaceRange(3, 7, "****");
  }
 Future<Null> alertDialog(BuildContext context,String msg){
   return showDialog<Null>(
      context: context,
      barrierDismissible: false,
      child: new AlertDialog(
        title: new Text(
          '温馨提示',
          style: new TextStyle(
            color: Colors.black54,
            fontSize: 18.0,
          ),
        ),
        content: new Text(msg),
        actions: <Widget>[
          new FlatButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: new Text('确定')),
        ],
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    double mapViewHeight = MediaQuery.of(context).size.height;
    double mapViewWidth = MediaQuery.of(context).size.width;
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(),
      body: ListView(
        children: <Widget>[
          Column(
            children: <Widget>[
              Container(
                width: mapViewWidth,
                padding: EdgeInsets.fromLTRB(0 ,30,0,15),
                child: Text(
                  "验证手机号",
                  style: TextStyle(fontSize: 30,color: Colors.blue),
                  textAlign: TextAlign.left,
                ),
              ),
              Container(
                width: mapViewWidth,
                padding: EdgeInsets.fromLTRB(0 ,0,0,0),
                child: Text(
                  "我们已将发送了手机号到您的手机",
                  style: TextStyle(fontSize: 15,color: Colors.grey),
                  textAlign: TextAlign.left,
                ),
              ),
              Container(
                width: mapViewWidth,
                padding: EdgeInsets.fromLTRB(0 ,30,0,15),
                child: Text(
                  secretnumber(),
                  style: TextStyle(fontSize: 36,color: Colors.blue),
                  textAlign: TextAlign.left,
                ),
              ),
            Stack(
                children: <Widget>[
                 Row(
                  children: <Widget>[
                    Padding(
                    padding: EdgeInsets.fromLTRB(5,5,0,0) ,
                      child:  kuang[0],
                        ),
                    Padding(
                      padding: EdgeInsets.fromLTRB(10,5,0,0) ,
                      child:     kuang[1],
                    ),
                    Padding(
                      padding: EdgeInsets.fromLTRB(10,5,0,0) ,
                      child:    kuang[2],
                    ),
                    Padding(
                      padding: EdgeInsets.fromLTRB(10,5,0,0) ,
                      child:   kuang[3],
                    ), Padding(
                      padding: EdgeInsets.fromLTRB(10,5,0,0) ,
                      child:   kuang[4],
                    ), Padding(
                      padding: EdgeInsets.fromLTRB(10,5,0,0) ,
                      child:  kuang[5],
                    ),
                  ],
                 ),
                  TextField(
                    style:  TextStyle(fontSize: 25,letterSpacing: 40),
                    keyboardType: TextInputType.phone,
                    controller: _textcontroller,
                    focusNode: _focusNode,
                    //cursorColor: Colors.white,
                    showCursor: false,
                    inputFormatters: <TextInputFormatter>[
                      WhitelistingTextInputFormatter.digitsOnly,//只输入数字
                      LengthLimitingTextInputFormatter(6)//限制长度
                    ],
                    decoration: InputDecoration(
                        border: InputBorder.none
                    ),
                  ),
                ],
              ),
              Container(
                padding: EdgeInsets.fromLTRB(mapViewWidth*0.5,10,0,0),
                child:  Container(
                  child: changewiget
                ),
              )
            ],
          )
        ],
      ),
    );
  }
  void httprquest()async{
    print("{'phoneNumbers':'"+widget.phonenumber+"','code':'"+randomcode+"'}");
    try{
      await HttpUtils().post("https://www.dzsbk.cn/smartDemo/wdssc-app/sms",data: "{'phoneNumbers':'"+widget.phonenumber+"','code':'"+randomcode+"'}").then((v){
        v.toString();
      });
    }
    catch(e)
    {
      alertDialog(context,"服务异常").then((val)
      {
        Navigator.pop( context);
      });
    }
    secretnumber();
  }
  @override
  void dispose() {
   timer.cancel();
    super.dispose();
   once=true;
  }
}

 class _greykuang  extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return   Container(
      width: 45,
      height: 45,
      // padding: EdgeInsets.fromLTRB(20,50,0,0),
      //color: Colors.red,
      decoration: new BoxDecoration(
        border: new Border.all(width: 1.0, color: Colors.grey),
        color: Colors.white,
        // borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
      ),
    );
  }
 }
class _bluekuang  extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return   Container(
      width: 45,
      height: 45,
      //padding: EdgeInsets.fromLTRB(20,50,0,0),
      //color: Colors.red,
      decoration: new BoxDecoration(
        border: new Border.all(width: 1.0, color: Colors.blue),
        color: Colors.white,
        // borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
      ),
    );
  }
}